/* eslint-disable */
import Request from './request';
import indexConfig from '@/config/index.config';
import mHelper from '@/utils/helper';
import store from '@/store';

const http = new Request();

// request全局参数设置
http.setConfig(config => {
	/* 设置全局配置 */
	config.baseUrl = indexConfig.baseUrl; /* 根域名不同 */
	const systemInfo = uni.getSystemInfoSync();
	const systemInfoHeaders = {
		'device-name': systemInfo.brand, // 设备名称
		width: systemInfo.screenWidth, // 屏幕宽度
		height: systemInfo.screenHeight, // 屏幕高度
		os: systemInfo.platform, // 客户端平台
		'os-version': systemInfo.system // 操作系统版本
	};
	config.header = {
		...config.header,
		...systemInfoHeaders
	};
	return config;
});

let isRefreshing = false;
let requests = [];
http.interceptor.request(
	config => {
		/* 请求之前拦截器 */
		config.header['x-api-key'] = uni.getStorageSync('accessToken');
		// 单商户
		// config.header['merchant-id'] = uni.getStorageSync('merchantId') || 1;
		return config;
	},
	error => {
		return Promise.reject(error);
	}
);

http.interceptor.response(
	async response => {
			/* 请求之后拦截器 */
			switch (response.data.code) {
				case '0':
					return response.data;
					break;
				case '101':
					mHelper.toast(response.data.message);
					return Promise.reject(response.data.message);
					break;
				case '405':  
					mHelper.toast('当前操作不被允许');
					return Promise.reject(response.data.message);
					break;
				case '404':
					mHelper.toast(response.data.message);
					return Promise.reject(response.data.message);
					break;
				case '429':
					mHelper.toast('请求过多，先休息一下吧');
					return Promise.reject(response.data.message);
					break;
				case '500':
					mHelper.toast('服务器打瞌睡了');
					return Promise.reject(response.data.message);
					break;
				case '110':
					mHelper.toast('帐号在别处登录了,正在重新登录!');
					mHelper.backToLogin();
				case '301':
					mHelper.toast(response.data.message);
					mHelper.backToLogin();
				default:
					mHelper.toast(response.data.message);
					return response.data;
					break;
			}
		},
		error => {
			return Promise.reject(error);
		}
);

export {
	http
};
